package com.xj.community.controller.interceptor;

import com.xj.community.Service.UserService;
import com.xj.community.dao.LoginTicketMapper;
import com.xj.community.entity.LoginTicket;
import com.xj.community.entity.User;
import com.xj.community.util.MyThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Component
public class LoginTicketInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    //该方法在处理请求前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        //根据cookie信息拿到login_ticket
        User user = null;
        if(cookies !=null){
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("ticket")){
                    //查询凭证
                    LoginTicket loginTicket = userService.findLoginTicket(cookie.getValue());
                    //检查凭证是否有效
                    if(loginTicket!=null && loginTicket.getStatus()!=1&&loginTicket.getExpired().after(new Date())){
                        user = userService.selectById(loginTicket.getUserId());
                    }
                }
            }
        }
        MyThreadLocal.setUser(user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = MyThreadLocal.getUser();
        if(user!=null && modelAndView !=null){
            modelAndView.addObject("loginUser",user);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       //模板引擎之后执行
        MyThreadLocal.remove();
    }
}
